﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WFNetLib;
using Microsoft.Office.Interop.Excel;

namespace ATCatcher
{
    public partial class Form1 : Form
    {
        ListViewItem li;
        private bool[] ComListening;//是否没有执行完invoke相关操作              
        private bool[] ComClosing;//是否正在关闭串口，执行Application.DoEvents， 并阻止再次invoke 
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ComListening = new bool[2];
            ComClosing = new bool[2];
            for (int i = 0; i < 2; i++)
            {
                ComListening[i] = false;
                ComClosing[i] = false;
            }                       
            try
            {
                serialPort1.Open();
            }
            catch { MessageBox.Show("深度计对应串口无法打开，无法获得深度计数据!"); }
            try
            {
                serialPort2.Open();
            }
            catch { MessageBox.Show("深度计对应串口无法打开，无法获得深度计数据!"); }
            li = listView1.Items.Add("");
            li.SubItems.Add("");
            li.SubItems.Add("");
            li.SubItems.Add("");
        }
        bool bNew=false;
        object o=new object();
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            byte rx;
            if (ComClosing[0])
                return;
            ComListening[0] = true;
            while (serialPort1.BytesToRead != 0)
            {
                int irx = serialPort1.ReadByte();
                if (irx == -1)
                    break;
                rx = (byte)irx;
                
                    this.Invoke((EventHandler)(delegate
                                        {
                                            if (rx != 0x0d)//非结束符
                                            {
                                                if (bNew)
                                                {
                                                    bNew = false;
                                                    lock (o)
                                                    {
                                                        li = listView1.Items.Add("");
                                                        li.SubItems.Add("");
                                                        li.SubItems.Add("");
                                                        li.SubItems.Add("");
                                                    }
                                                }
                                                li.Text += (char)rx;
                                                li.SubItems[2].Text += rx.ToString("X2") + " ";
                                            }
                                            else
                                            {
                                                bNew = true;
                                                li.SubItems[2].Text += rx.ToString("X2") + " ";
                                            }
                                        }));
                
            }
            ComListening[0] = false;
        }

        private void serialPort2_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            byte rx;
            if (ComClosing[1])
                return;
            ComListening[1] = true;
            while (serialPort2.BytesToRead != 0)
            {
                int irx = serialPort2.ReadByte();
                if (irx == -1)
                    break;
                rx = (byte)irx;
                
                    this.Invoke((EventHandler)(delegate
                                        {
                                            lock (o)
                                            {
                                                if (rx != 0x0d)//非结束符
                                                {
                                                    li.SubItems[1].Text += (char)rx;
                                                    li.SubItems[3].Text += rx.ToString("X2") + " ";
                                                }
                                                else
                                                {
                                                    li.SubItems[1].Text += "@";
                                                    li.SubItems[3].Text += rx.ToString("X2") + " ";
                                                }
                                            }
                                        }));
                
            }
            ComListening[1] = false;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            for (int i = 0; i < 2; i++)
                ComClosing[i] = true;
            for (int i = 0; i < 2; i++)
            {
                while (ComListening[i])
                    System.Windows.Forms.Application.DoEvents();
            }
            serialPort1.Close();
            serialPort2.Close();
        }

        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 1)
            {
                ListViewItem ll = listView1.SelectedItems[0];
                Form2 f = new Form2(ll.Text,ll.SubItems[2].Text,ll.SubItems[1].Text.Replace("@","\r\n"),ll.SubItems[3].Text);
                f.ShowDialog();
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 2; i++)
                ComClosing[i] = true;
            ExcelExport eex = new ExcelExport(listView1.Items.Count);
            eex.ExcelWorkbookCallbackProc = new ExcelExport.ExcelWorkbookCallback(ExcelWorkbookCallbackProc);
            eex.ExcelExportProc();
            for (int i = 0; i < 2; i++)
            {
                ComClosing[i] = false;
            }  
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 2; i++)
                ComClosing[i] = true;

            listView1.Items.Clear();
            li = listView1.Items.Add("");
            li.SubItems.Add("");
            li.SubItems.Add("");
            li.SubItems.Add("");
            for (int i = 0; i < 2; i++)
            {
                ComClosing[i] = false;
            } 
        }
        private bool ExcelWorkbookCallbackProc(Workbook wBook, int index)
        {
            Worksheet wSheet = (Worksheet)wBook.Worksheets[wBook.Worksheets.Count];
            Range dr;
            if (index == -1)
            {
                wSheet.Name = "AT数据";
                wSheet.Cells[1, 1] = "软件发送";
                wSheet.Cells[1, 3] = "软件发送HEX";
                wSheet.Cells[1, 2] = "模块发送";
                wSheet.Cells[1, 4] = "模块发送HEX";
                dr = wSheet.get_Range("A1", "D1");
                dr.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.DarkOrange);
                dr.Interior.Pattern = XlPattern.xlPatternSolid;
            }
            else if (index == int.MaxValue)
            {
                dr = wSheet.get_Range("A1", "D" + (listView1.Items.Count + 1).ToString());
                dr.Columns.AutoFit();
                dr.HorizontalAlignment = XlHAlign.xlHAlignCenter;
                dr.Borders.LineStyle = XlLineStyle.xlContinuous;
            }
            else
            {
                this.Invoke((EventHandler)(delegate
                   {
                       ListViewItem ll = listView1.Items[index];
                       wSheet.Cells[2 + index, 1] = ll.Text;
                       wSheet.Cells[2 + index, 3] = ll.SubItems[2].Text;
                       wSheet.Cells[2 + index, 2] = ll.SubItems[1].Text.Replace("@", "\r\n");
                       wSheet.Cells[2 + index, 4] = ll.SubItems[3].Text;
                   }));
                if (index % 2 == 1)
                {
                    dr = wSheet.get_Range("A" + (2 + index).ToString(), "D" + (2 + index).ToString());
                    dr.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGray);
                    dr.Interior.Pattern = XlPattern.xlPatternSolid;
                }
            }
            return true;
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {            
            Form3 f = new Form3();
            f.ShowDialog();
        }
    }
}
